package com.funsport.controller.mobile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.Result;
import com.funsport.entity.PointOrder;
import com.funsport.entity.PointProduct;
import com.funsport.service.IPointOrderService;
import com.funsport.service.IPointProductService;
import com.funsport.security.JwtTokenProvider;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 移动端积分商城Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/mobile/mall")
@RequiredArgsConstructor
@Tag(name = "移动端积分商城")
public class MobilePointMallController {
    
    private final IPointProductService pointProductService;
    private final IPointOrderService pointOrderService;
    private final JwtTokenProvider jwtTokenProvider;
    
    @Operation(summary = "获取商品列表")
    @GetMapping("/products")
    public Result<Page<PointProduct>> getProducts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String category
    ) {
        try {
            // 只展示上架商品
            Page<PointProduct> result = pointProductService.getProductList(page, pageSize, category, "active");
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取商品列表失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "获取热门商品")
    @GetMapping("/products/hot")
    public Result<Page<PointProduct>> getHotProducts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "6") Integer pageSize
    ) {
        try {
            Page<PointProduct> result = pointProductService.getHotProducts(page, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取热门商品失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "获取商品详情")
    @GetMapping("/products/{id}")
    public Result<PointProduct> getProductDetail(@PathVariable Long id) {
        try {
            PointProduct product = pointProductService.getById(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            return Result.success(product);
        } catch (Exception e) {
            log.error("获取商品详情失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "兑换商品")
    @PostMapping("/exchange")
    public Result<String> exchange(
            @RequestParam Long productId,
            @RequestParam(defaultValue = "1") Integer quantity,
            @RequestParam(required = false) String receiverName,
            @RequestParam(required = false) String receiverPhone,
            @RequestParam(required = false) String receiverAddress,
            HttpServletRequest request
    ) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = token != null ? jwtTokenProvider.getUserIdFromToken(token) : null;
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            String orderNo = pointOrderService.exchange(userId, productId, quantity, 
                receiverName, receiverPhone, receiverAddress);
            return Result.success(orderNo, "兑换成功");
        } catch (Exception e) {
            log.error("兑换失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "获取我的兑换记录")
    @GetMapping("/orders")
    public Result<Page<PointOrder>> getMyOrders(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            HttpServletRequest request
    ) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = token != null ? jwtTokenProvider.getUserIdFromToken(token) : null;
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            Page<PointOrder> result = pointOrderService.getUserOrders(userId, page, pageSize, status);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取兑换记录失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    @Operation(summary = "取消订单")
    @PostMapping("/orders/cancel")
    public Result<Void> cancelOrder(
            @RequestParam String orderNo,
            HttpServletRequest request
    ) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = token != null ? jwtTokenProvider.getUserIdFromToken(token) : null;
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            pointOrderService.cancel(orderNo, userId);
            return Result.success();
        } catch (Exception e) {
            log.error("取消订单失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
}

